﻿using Dapper;
using Entity;
using ServiceCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{

    public interface Irole_servier
    {
        ResultListModel<rk_role> get_pagelist(Base_List_Params query);
        ResultObjModel get_model(string rid);
        ResultModel save_item(sys_role_Params model);
        ResultModel del_item(string rid); 
        ResultModel BindMenuToRole(SaveMenuToRole Params); 
    }
    public class role_servier : Irole_servier
    {
        private readonly IToole_DI _tool;
        private readonly Imenu_service _service;
        public role_servier(IToole_DI Tool, Imenu_service Service)
        {
            _tool = Tool;
            _service = Service;
        }

        #region 角色 
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<rk_role> get_pagelist(Base_List_Params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<rk_role>>(result =>
            {
                string sql = "select * from rk_role";
                string where = " where 1=1 ";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    where += $" and role_name like @role_name";
                    query_dy.role_name = query.SerchKeyword;
                }
                result = _tool.di_db.GetPageList<rk_role>(sql, where, "addtime", query_dy, query.IsPage, query.page, query.pagesize);
                return result;
            });
        }

        /// <summary>
        /// 获取菜单详情
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_model(string rid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var MenuModel = _tool.di_db.GetModel<rk_role>(new string[] { "rid=@rid" }, new { rid = rid });
                if (MenuModel == null)
                {
                    result.code = 1;
                    result.msg = "角色信息不存在";
                }
                else
                {
                    result.code = 0;
                    result.msg = "Success";
                    object toLable = new object();
                    object toLable2 = new object();
                    var obj = _service.GetMenu(ref toLable, MenuModel.rid);
                    var obj2 = _service.GetMenu(ref toLable2, MenuModel.rid, false, menu_type.WorkApp);
                    result.data = new { role = MenuModel, bindmenu = obj, toLable, toLable2, bindworkmenu = obj2 };
                }
                return result;
            });
        }
        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel save_item(sys_role_Params model)
        {
            ResultModel result = new ResultModel();
            try
            {
                #region  基础验证 
                if (string.IsNullOrWhiteSpace(model.role_model.role_name))
                {
                    result.code = 1;
                    result.msg = "角色名称不能为空";
                    return result;
                }
                var ExistModel = _tool.di_db.GetModel<rk_role>(new string[] { "role_name=@role_name", "rid<>@rid" }, new { model.role_model.role_name, model.role_model.rid });
                if (ExistModel != null)
                {
                    result.code = 1;
                    result.msg = "角色名称已存在";
                    return result;
                } 
                #endregion
                #region 数据处理 
                if (string.IsNullOrWhiteSpace(model.role_model.rid))
                {
                    //添加
                    model.role_model.rid = _tool.di_getid.IGet_SnowFlake_Id;
                    model.role_model.addtime = DateTime.Now;   
                    List<rk_role_menu> NewMenuList = new List<rk_role_menu>();
                    foreach (var item in model.ids)
                    {
                        NewMenuList.Add(new rk_role_menu()
                        {
                            rmid = _tool.di_getid.IGet_SnowFlake_Id,
                            mid = item,
                            rid = model.role_model.rid
                        });
                    }
                    string error = "";
                    int resultCount = _tool.di_db.StartTran((conn, tran) =>
                    {
                        int tranrow = 0;
                        tranrow += conn.Execute(_tool.di_db.AddBySqlStr<rk_role>(), model.role_model, tran);
                        //重新添加对应绑定关系 
                        if (NewMenuList.Any())
                        {
                            tranrow += conn.Execute(_tool.di_db.AddBySqlStr<rk_role_menu>(), NewMenuList, tran);
                        }
                        return tranrow;
                    }, ref error);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "添加成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败 DB error";
                    }
                }
                else
                {
                    //编辑
                    var needupdate = _tool.di_db.GetModel<rk_role>(new string[] { "rid=@rid" }, new { model.role_model.rid });
                    if (needupdate == null)
                    {
                        result.code = 1;
                        result.msg = "修改信息不存在";
                        return result;
                    }
                    
                    List<rk_role_menu> NewMenuList = new List<rk_role_menu>();
                    foreach (var item in model.ids)
                    {
                        NewMenuList.Add(new rk_role_menu()
                        {
                            rmid = _tool.di_getid.IGet_SnowFlake_Id,
                            mid = item,
                            rid = model.role_model.rid
                        });
                    } 
                    string error = "";
                    int resultCount = _tool.di_db.StartTran((conn, tran) =>
                    {
                        int tranrow = 0;
                        tranrow += conn.Execute(_tool.di_db.UpdateBySqlstr<rk_role>(new string[] { "role_name" }, new string[] { "rid=@rid" }), new
                        {
                            model.role_model.role_name, 
                            model.role_model.rid,
                        }, tran); 
                        //先删除当前角色的所有绑定菜单信息
                        tranrow += conn.Execute("delete from rk_role_menu where rid=@rid", new { rid = model.role_model.rid }, tran); 
                        //重新添加对应绑定关系 
                        if (NewMenuList.Any())
                        { 
                            tranrow += conn.Execute(_tool.di_db.AddBySqlStr<rk_role_menu>(), NewMenuList, tran);
                        }
                        return tranrow;
                    }, ref error);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改成功 DB error";
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }
        private string[] can_t_delete = new string[] { "Customer", "technology_Customer", "Approval", "SuperAdmin", "all_Customer", "Sale", "Sales_Manager", "Work_Manager", "Worker", "Work_QA", "Finance_Manager" };
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        public ResultModel del_item(string rid)
        {
            return CoreStartDo.ResultAction(result=> {
                if (can_t_delete.Contains(rid))
                {
                    result.code = 1;
                    result.msg = "无法删除系统相关项";
                    return result;
                }
                var resultCount = _tool.di_db.do_Execute("delete from rk_role where rid=@rid", new { rid });
                if (resultCount > 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败,没有条目被改变";
                }
                return result;
            }); 
        }
        #endregion
        #region 绑定角色和菜单
        /// <summary>
        /// 绑定菜单到角色
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        public ResultModel BindMenuToRole(SaveMenuToRole Params)
        {
            ResultModel result = new ResultModel();
            try
            {
                #region 开始基础验证
                if (string.IsNullOrWhiteSpace(Params.role_id))
                {
                    result.code = 1;
                    result.msg = "必须指定绑定菜单的角色";
                    return result;
                }
                #endregion
                List<rk_role_menu> NewMenuList = new List<rk_role_menu>();
                foreach (var item in Params.Menu_ids)
                {
                    NewMenuList.Add(new rk_role_menu()
                    {
                        rmid = _tool.di_getid.IGet_SnowFlake_Id,
                        mid = item,
                        rid = Params.role_id
                    });
                }
                string error = "";
                int rows = _tool.di_db.StartTran((conn, tran) =>
                {
                    int tranrow = 0;
                    //先删除当前角色的所有绑定菜单信息
                    tranrow += conn.Execute("delete from rk_role_menu where rid=@rid", new { rid = Params.role_id }, tran);
                    //重新添加对应绑定关系 
                    if (NewMenuList.Any())
                    {
                        tranrow += conn.Execute(_tool.di_db.AddBySqlStr<rk_role_menu>(), NewMenuList, tran);
                    }
                    return tranrow;
                }, ref error);
                if (rows == 0)
                {
                    if (error != "")
                    {
                        result.code = 1;
                        result.msg = error;
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "绑定菜单异常:db error";
                    }
                }
                else
                {
                    result.code = 0;
                    result.msg = "绑定成功";
                }

            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }
        #endregion
    }
}
